package cn.lzm.protocol;

import cn.lzm.serializer.Serializer;
import cn.lzm.serializer.SerializerFactoryV2;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;
import java.util.Objects;

/**
 * @author lzm
 * @Date 2024/11/5
 * @description 协议消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 编码
     * 将消息转为buffer
     *
     * @param protocolMessage 消息
     * @return buffer
     * @throws IOException io exception
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException{
        if (protocolMessage == null || protocolMessage.getHeader() == null) {
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocolMessage.getHeader();
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getSerializerByKey(header.getSerializer());
        if (Objects.isNull(serializerEnum)) {
            throw new RuntimeException("序列化器不存在！");
        }
        Serializer serializer = SerializerFactoryV2.getSerializer(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
